package com.haoyun.mirage.auth.provider;

import com.haoyun.mirage.auth.security.CustomerUserDetails;
import com.haoyun.mirage.auth.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import javax.security.auth.login.AccountLockedException;

/**
 * Created by twg on 2018/5/31.
 *
 * @see org.springframework.security.authentication.ProviderManager
 */
@Slf4j
@Component("userAuthenticationProvider")
public class UserAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private IUserService userService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = (String) authentication.getCredentials();
        CustomerUserDetails userDetail = (CustomerUserDetails) userService.loadUserByUsername(username);
        if (userDetail == null) {
            throw new UsernameNotFoundException("该账号不存在");
        }
        if (!userDetail.isEnabled()){
            throw new DisabledException("该账号已失效");
        }
        if (!userDetail.isAccountNonExpired()) {
            throw new AccountExpiredException("该账号已过期");
        }
        if (!userDetail.isAccountNonLocked()) {
            throw new LockedException("该账号已锁定");
        }
        if (!userDetail.isCredentialsNonExpired()) {
            throw new CredentialsExpiredException("该账号密码已过期");
        }
        if (!passwordEncoder.matches(password + userDetail.getSalt(), userDetail.getPassword())) {
            throw new BadCredentialsException("账号密码错误!");
        }
        return new UsernamePasswordAuthenticationToken(userDetail, userDetail.getPassword(), userDetail.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }
}
